import { expect } from '@jest/globals';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.NativeC
  },
  modulesOption: {}
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const entryModulePath = project.getModule('entry').moduleRootPath();

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);
  const buildPathExist =
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build'));

  const commandsClean = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'clean'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const resultClean = await runHvigorAsync(projectRoot, commandsClean);
  const buildPathCleanExist =
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build'));

  record.addStep('执行hap编译构建', result);
  record.addStep('执行clean', resultClean);
  expect(buildPathExist).toBe(true);
  expect(buildPathCleanExist).toBe(false);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(resultClean.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_ZOS_MENU_BUILD_HOS_api10_STAGE_002')
  .description('Stage模型菜单栏Clean Project')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).ohpmInstall(IsEnable.Enable).build())
  .testFun(testFun('entry'))
  .load();
